/**
 * localStorage获取值
 * @param key storage key
 */
export const getLocalStorage = (key: string) => {
    const storeData = localStorage.getItem(key);
    if (storeData === null) return null;

    const jsonObj: { value?: any, expires: number, time: number } = JSON.parse(storeData);
    if (jsonObj.expires !== 0 && (Date.now() - jsonObj.time > jsonObj.expires)) {
        // 获取数据的时候判断一下是否过期，如果过期了，就把它清除
        localStorage.removeItem(key);
        return null;
    }
    return jsonObj.value;
}

/**
 * localStorage设置值，带过期时间
 * @param key storage key
 * @param value 值
 * @param expires 过期时间，单位ms
 */
export const setLocalStorage = (key: string, value: any, expires?: number) => {
    const storeData = {
        value: value,
        time: Date.now(),
        expires: expires || 0
    };
    const userStr = JSON.stringify(storeData);
    localStorage.setItem(key, userStr)
}

export const clearLocalStorage = () => {
    localStorage.clear();
}